/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/parser/deserializer/InetSocketAddressDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: InetSocketAddressDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.parser.deserializer;

import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.elancom.framework.commons.json.JSONException;
import com.elancom.framework.commons.json.parser.DefaultJSONParser;
import com.elancom.framework.commons.json.parser.JSONLexer;
import com.elancom.framework.commons.json.parser.JSONToken;

public class InetSocketAddressDeserializer implements ObjectDeserializer {

	public final static InetSocketAddressDeserializer instance = new InetSocketAddressDeserializer();

	@Override
	@SuppressWarnings("unchecked")
	public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
		final JSONLexer lexer = parser.getLexer();

		if (lexer.token() == JSONToken.NULL) {
			lexer.nextToken();
			return null;
		}

		parser.accept(JSONToken.LBRACE);

		InetAddress address = null;
		int port = 0;
		for (;;) {
			final String key = lexer.symbol(parser.getSymbolTable());
			lexer.nextToken();

			if (key.equals("address")) {
				parser.accept(JSONToken.COLON);
				address = parser.parseObject(InetAddress.class);
			} else if (key.equals("port")) {
				parser.accept(JSONToken.COLON);
				if (lexer.token() != JSONToken.LITERAL_INT) {
					throw new JSONException("port is not int");
				}
				port = lexer.intValue();
				lexer.nextToken();
			} else {
				parser.accept(JSONToken.COLON);
				parser.parse();
			}

			if (lexer.token() == JSONToken.COMMA) {
				lexer.nextToken();
				continue;
			}

			break;
		}

		parser.accept(JSONToken.RBRACE);

		return (T) new InetSocketAddress(address, port);
	}

	@Override
	public int getFastMatchToken() {
		return JSONToken.LBRACE;
	}
}
